<?php


namespace App\Rules;


use App\Facade\SystemBin;
use Illuminate\Contracts\Validation\Rule;

class BankCardNumber implements Rule
{
    private $binShort = false;
    public $binInfo;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($binShort = false)
    {
        $this->binShort = $binShort;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if (strlen($value) < 9) {
            return false;
        }
        $binInfo = SystemBin::checkCard($value);
        if (empty($binInfo)) {
            return false;
        }
        $this->binInfo = $binInfo;
        if ($this->binShort !== false) {
            if ($this->binShort != $binInfo->short_name) {
                return false;
            }
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return '银行卡号格式错误，或与发卡行不匹配';
    }
}
